<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="20" style="border-right: 1px solid #dddddd;margin-top: 10px;">
        <div v-if="showStep === 'base'">
          <el-form :model="lesson" :rules="lessonRules" ref="lessonRef" label-width="120px">
            <el-form-item label="名称：" prop="name">
              <el-input size="mini" v-model="lesson.name" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="开始时间：" prop="startTime">
              <el-date-picker
                v-model="lesson.startTime"
                type="datetime"
                placeholder="选择开始时间"
                class="input-text"
                :default-time="new Date(2000, 0, 1, 0, 0, 0)"
                size="mini"
                @change="changeStartTime"
                style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间：" prop="endTime">
              <el-date-picker
                v-model="lesson.endTime"
                type="datetime"
                placeholder="选择结束时间"
                class="input-text"
                :default-time="new Date(2000, 0, 1, 22, 0, 0)"
                size="mini"
                @change="changeEndTime"
                style="width: 100%;"></el-date-picker>
            </el-form-item>
            <el-form-item label="分类：" prop="cidList">
              <el-cascader style="width: 100%;"
                           size="mini"
                           v-model="selectCidList"
                           :props="{ multiple: true, checkStrictly: true }"
                           :options="categoryOptions"
                           @change="changeCategory">
              </el-cascader>
            </el-form-item>
            <el-form-item label="简介：" prop="phrase">
              <el-input size="mini" v-model="lesson.phrase" placeholder="请输入简介"></el-input>
            </el-form-item>
            <el-form-item label="作业：">
              <el-input size="mini" type="textarea" :rows="10" v-model="lesson.homework" placeholder="请输入作业内容"></el-input>
              <div class="homework-attachment">
                <upload
                  list-type="text"
                  :on-upload-success="onUploadHomeworkAttachmentSuccess"
                  :on-upload-remove="onUploadHomeworkAttachmentRemove"
                  :files="uploadHomeworkData.files"
                  :upload-url="uploadHomeworkData.url"
                  :limit="1"
                  accept="image/*,video/*,audio/*,application/*">
                </upload>
              </div>
            </el-form-item>
            <el-form-item label="海报：" prop="image">
              <upload
                :on-upload-success="onUploadImageSuccess"
                :on-upload-remove="onUploadImageRemove"
                :files="uploadData.files"
                :upload-url="uploadData.url"
                :limit="1"
                accept="image/jpeg,image/gif,image/png">
              </upload>
              <span class="upload-image-tips">图片建议：尺寸 1920 x 1200 像素，大小7M以下</span>
            </el-form-item>
            <el-form-item label="详情描述：" prop="introduction">
              <tiny-mce :height="300" v-model="lesson.introduction"></tiny-mce>
            </el-form-item>
            <el-button size="mini" style="display:block;margin:50px auto;" @click="submitBaseInfo">提交</el-button>
          </el-form>
        </div>
        <div v-if="showStep === 'content'" style="position: relative;min-height: 500px;">
          <div><el-button size="mini" @click="showChapter">新增章节</el-button></div>
          <div style="margin-top: 20px;">
            <el-table default-expand-all :data="contentList" :show-header="false" :highlight-current-row="true" style="width: 100%">
              <el-table-column type="expand">
                <template #default="props">
                  <div class="tips">{{props.row.phrase}}</div>
                  <el-card class="box-card" v-for="section in props.row.chapterSectionList" :key="section.title" style="margin-top: 20px;">
                    <template #header>
                      <div class="clearfix" style="line-height: 28px;">
                        <span>{{section.title}}</span>
                        <span style="float: right;">
                          <el-button size="mini" @click="showChapterSection(props.row.id, section)">修改</el-button>
                          <el-button size="mini" @click="deleteChapterSection(props.row.id)">删除</el-button>
                        </span>
                      </div>
                    </template>
                    <div class="table-wrapper">
                      <div class="tips">{{section.phrase}}</div>
                      <video :src="section.url" controls="controls" :style="{'margin-top:20px;': !!section.phrase}" style="background: #000;width: 400px;height: 300px"></video>
                    </div>
                  </el-card>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="标题"></el-table-column>
              <el-table-column label="操作">
                <template #default="r">
                  <span style="float: right;">
                    <el-button @click="showChapterSection(r.row.id)" size="mini">新增章节内容</el-button>
                    <el-button @click="showChapter(r.row)" size="mini">修改</el-button>
                    <el-button @click="deleteChapter(r.row.id)" size="mini">删除</el-button>
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div v-if="showStep === 'publish'" style="position: relative;height: 500px;">
          <div style="position:absolute;left:50%;top:40%;-webkit-transform:translateX(-50%);transform:translateX(-50%);">
            <p style="margin: 0 0 30px 0;">当前状态：{{statusMap[lesson.status]}}</p>
            <el-button size="mini" type="success" @click="publish" :disabled="lesson.status === 'published'">马上发布</el-button>
            <el-button size="mini" type="danger" @click="unPublish" :disabled="lesson.status === 'unpublished'">移入草稿</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="4" style="position: relative;">
        <div style="height: 500px;position: absolute;margin: 10px 17%;">
          <el-steps direction="vertical" :active="stepActive">
            <el-step v-for="(step) in steps" :key="step.key" @click="stepClick(step.key)" :class="{'step-active': showStep === step.key}" :title="step.name"></el-step>
          </el-steps>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="编辑章节" v-model="showChapterDialog" :before-close="hideChapter">
      <el-form :model="lessonChapter" :rules="lessonChapterRules" ref="lessonChapterRef">
        <el-form-item label="标题：" label-width="120px" prop="title">
          <el-input size="mini" v-model="lessonChapter.title" placeholder="请输入标题" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介：" label-width="120px" prop="phrase">
          <el-input size="mini" v-model="lessonChapter.phrase" type="textarea" :rows="4" placeholder="请输入简介"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="mini" @click="hideChapter">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitChapter">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="编辑章节内容" v-model="showChapterSectionDialog" :before-close="hideChapterSection">
      <el-form :model="lessonChapterSection" :rules="lessonChapterSectionRules" ref="lessonChapterSectionRef">
        <el-form-item label="标题：" label-width="120px" prop="title">
          <el-input size="mini" v-model="lessonChapterSection.title" placeholder="请输入标题" autocomplete="off"></el-input>
        </el-form-item>
        <!--        <el-form-item label="视频方式：" label-width="120px">-->
        <!--          <el-radio v-model="lessonChapterSectionUrlType" label="link">视频链接</el-radio>-->
        <!--          <el-radio v-model="lessonChapterSectionUrlType" label="upload">视频上传</el-radio>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="视频链接：" label-width="120px" prop="url" v-if="lessonChapterSectionUrlType === 'link'">-->
        <!--          <el-input size="mini" v-model="lessonChapterSection.url" placeholder="请输入视频地址" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="视频上传：" label-width="120px" prop="url">
          <upload
            :on-before-upload="onBeforeUploadVideo"
            :on-upload-success="onUploadVideoSuccess"
            :on-upload-remove="onUploadVideoRemove"
            :files="uploadVideoData.files"
            :upload-url="uploadVideoData.url"
            :limit="1"
            listType="text"
            accept="audio/mp4,video/mp4">
          </upload>
        </el-form-item>
        <el-form-item label="简介：" label-width="120px" prop="phrase">
          <el-input size="mini" v-model="lessonChapterSection.phrase" type="textarea" :rows="4" placeholder="请输入简介"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="mini" @click="hideChapterSection">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitChapterSection">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  import {ref} from "vue"
  import {useRoute} from "vue-router"
  import router from "../../../router"
  import {findCategoryList, toTree, getAllParent} from "../../../api/learn/category"
  import {saveBaseInfo, updateBaseInfo, getBaseInfo, publishLesson, unPublishLesson,
    saveLessonChapter, updateLessonChapter, deleteLessonChapter, getLessonChapterList,
    saveLessonChapterSection, updateLessonChapterSection, deleteLessonChapterSection} from "../../../api/learn/lesson"
  import Upload from "../../../components/Uplaod/index"
  import TinyMce from "../../../components/Tinymce"
  import {success, confirm} from "../../../util/tipsUtils";

  export default {
    components:{
      Upload,
      TinyMce
    },
    setup() {
      const route = useRoute()
      const isUpdate = !!route.query.id
      let showStep = ref("")
      // 基本信息
      const uploadData = ref({
        url: process.env.VUE_APP_BASE_API + "/oss/learn/lesson/image",
        files: []
      })
      const uploadHomeworkData = ref({
        url: process.env.VUE_APP_BASE_API + "/oss/learn/lesson-homework/image",
        files: []
      })
      const categoryOptions = ref([])
      const selectCidList = ref([])
      const lesson = ref({
        id: "",
        name: "",
        startTime: "",
        endTime: "",
        image: "",
        cidList: [],
        phrase: "",
        introduction: ""
      })
      const lessonRules = {
        name: [{ required: true, message: "请输入标题", trigger: "blur" }],
        startTime: [{ required: true, message: "请选择时间", trigger: "change" }],
        endTime: [{ required: true, message: "请选择时间", trigger: "change" }],
        phrase: [{ required: true, message: "请输入简介", trigger: "blur" }],
        cidList: [{ required: true, message: "请选择分类", trigger: "change" }],
        introduction: [{ required: true, message: "请输入描述", trigger: "blur" }],
        image: [{ required: true, message: "请选择海报", trigger: "change" }],
      }
      // 加载基本信息
      const loadBaseInfo = () => {
        let id = route.query.id;
        if (!id) { return; }
        getBaseInfo(id, function (res) {
          console.log(res)
          lesson.value = res;
          selectCidList.value = getAllParent(categoryOptions.value, res.cidList);
          lesson.value.cidList = []
          uploadData.value.files = [{name: "海报", url: lesson.value.image}]
          if (lesson.value.homeworkAttachment) {
            uploadHomeworkData.value.files = [{name: "作业附件", url: lesson.value.homeworkAttachment}]
          }
          for (const valElement of selectCidList.value) {
            lesson.value.cidList.push(valElement[valElement.length - 1])
          }
        })
      }
      // 获取分类
      const loadCategory = () => {
        findCategoryList(0, true, (res) => {
          if (res && res.length) {
            categoryOptions.value = toTree(res);
            loadBaseInfo();
          }
        })
      }
      // 选择分类
      const changeCategory = (val) => {
        lesson.value.cidList = []
        for (const valElement of val) {
          lesson.value.cidList.push(valElement[valElement.length - 1])
        }
      }
      // 选择时间
      const changeStartTime = (val) => {
        lesson.value.startTime = val
      }
      // 选择时间
      const changeEndTime = (val) => {
        lesson.value.endTime = val
      }
      // 上传图片成功
      const onUploadImageSuccess = (res) => {
        console.log(res)
        lesson.value.image = res.data
      }
      // 删除图片
      const onUploadImageRemove = () => {
        lesson.value.image = ""
        uploadData.value.files = []
      }
      // 上传附件成功
      const onUploadHomeworkAttachmentSuccess = (res) => {
        console.log(res)
        lesson.value.homeworkAttachment = res.data
      }
      // 删除附件成功
      const onUploadHomeworkAttachmentRemove = () => {
        lesson.value.homeworkAttachment = ""
        uploadHomeworkData.value.files = []
      }
      // 提交基本信息
      const lessonRef = ref(null)
      const submitBaseInfo = () => {
        lessonRef.value.validate((valid) => {
          if (!valid) { return false }
          if (isUpdate) {
            if (typeof lesson.value.startTime === "string") {
              lesson.value.startTime = new Date(lesson.value.startTime)
            }
            if (typeof lesson.value.endTime === "string") {
              lesson.value.endTime = new Date(lesson.value.endTime)
            }
            updateBaseInfo(lesson.value, function (res) {
              if (res && res.id) {
                lesson.value.id = res.id;
                success("编辑成功")
                let path = route.fullPath;
                router.push({path, query: {id: lesson.value.id, step: "content"} });
                showStep.value = "content";
              }
            })
          } else {
            if (typeof lesson.value.startTime === "string") {
              lesson.value.startTime = new Date(lesson.value.startTime)
            }
            if (typeof lesson.value.endTime === "string") {
              lesson.value.endTime = new Date(lesson.value.endTime)
            }
            saveBaseInfo(lesson.value, function (res) {
              if (res && res.id) {
                lesson.value.id = res.id;
                success("新增成功")
                let path = route.fullPath;
                router.push({path, query: {id: lesson.value.id, step: "content"} });
                showStep.value = "content";
              }
            })
          }
        })
      }

      // 内容
      const contentList = ref([])
      const showChapterDialog = ref(false)
      const lessonChapter = ref({
        id: "",
        lessonId: "",
        title: "",
        phrase: ""
      })
      const lessonChapterRules = {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        phrase: [{ required: true, message: "请输入简介", trigger: "blur" }]
      }
      const showChapterSectionDialog = ref(false)
      const lessonChapterSection = ref({
        id: "",
        lessonChapterId: "",
        title: "",
        url: "",
        phrase: ""
      })
      const lessonChapterSectionRules = ref({
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        url: [{ required: true, message: "请输入视频地址", trigger: "blur" }],
        phrase: [{ required: true, message: "请输入简介", trigger: "blur" }]
      })
      const loadContent = () => {
        let id = route.query.id;
        if (!id) { return; }
        getLessonChapterList({lessonId: id}, (res) => {
          if (res && res.list) {
            contentList.value = res.list;
          }
        })
      }
      const showChapter = (chapter) => {
        showChapterDialog.value = true;
        if (chapter && chapter.id) {
          lessonChapter.value = chapter;
        } else {
          lessonChapter.value = {
            lessonId: lesson.value.id,
            id: "",
            title: "",
            phrase: ""
          }
        }
      }
      const hideChapter = () => {
        showChapterDialog.value = false;
        lessonChapter.value = {id: "", lessonId: "", title: "", phrase: ""}
      }
      const uploadVideoData = ref({
        url: process.env.VUE_APP_BASE_API + "/oss/learn/lesson/video",
        files: []
      })
      const showChapterSection = (lessonChapterId, chapterSection) => {
        showChapterSectionDialog.value = true;
        if (chapterSection && chapterSection.id) {
          lessonChapterSection.value = chapterSection;
          uploadVideoData.value.files = [{name: "视频.mp4", url: lessonChapterSection.value.url}]
        } else {
          lessonChapterSection.value = {
            lessonChapterId: lessonChapterId,
            id: "",
            title: "",
            url: "",
            phrase: "",
            totalTime: 0
          }
        }
      }
      const hideChapterSection = () => {
        showChapterSectionDialog.value = false;
        lessonChapterSection.value = {id: "", lessonChapterId: "", title: "", url: "", phrase: "", totalTime: 0}
      }
      const deleteChapter = (id) => {
        confirm("确认删除吗？", "提示", () => {
          deleteLessonChapter({id: id}, () => {
            success("删除成功")
            loadContent()
          })
        })
      }
      const deleteChapterSection = (id) => {
        confirm("确认删除吗？", "提示", () => {
          deleteLessonChapterSection({id: id}, () => {
            success("删除成功")
            loadContent()
          })
        })
      }
      const lessonChapterRef = ref(null)
      const submitChapter = () => {
        lessonChapterRef.value.validate((valid) => {
          if (!valid) { return false }
          if (lessonChapter.value.id) {
            updateLessonChapter(lessonChapter.value, function () {
              success("编辑成功")
              hideChapter()
              loadContent()
            })
          } else {
            saveLessonChapter(lessonChapter.value, function () {
              success("新增成功")
              hideChapter()
            })
          }
        })
      }
      const lessonChapterSectionRef = ref(null)
      const submitChapterSection = () => {
        lessonChapterSectionRef.value.validate((valid) => {
          if (!valid) { return false }
          if (lessonChapterSection.value.id) {
            updateLessonChapterSection(lessonChapterSection.value, function () {
              success("编辑成功")
              hideChapterSection()
              loadContent()
            })
          } else {
            saveLessonChapterSection(lessonChapterSection.value, function () {
              success("新增成功")
              hideChapterSection()
              loadContent()
            })
          }
        })
      }
      // 上传视频成功
      const onUploadVideoSuccess = (res) => {
        console.log(res)
        lessonChapterSection.value.url = res.data
        uploadVideoData.value.files = [{name: "视频.mp4", url: res.data}]
      }
      // 删除视频
      const onUploadVideoRemove = () => {
        lessonChapterSection.value.url = ""
        uploadVideoData.value.files = []
      }
      const onBeforeUploadVideo = (file) => {
        let videoUrl = URL.createObjectURL(file);
        let audioElement = new Audio(videoUrl);
        audioElement.addEventListener("loadedmetadata", () => {
          //时长为秒，小数，182.36
          let duration = audioElement.duration;
          lessonChapterSection.value.totalTime = duration;
        });
      }
      const lessonChapterSectionUrlType = ref("link")
      // 发布页面
      const statusMap = {
        unpublished: "草稿箱",
        published: "已发布",
        deleted: "已删除"
      }
      const publish = () => {
        publishLesson({id: lesson.value.id}, () => {
          success("发布成功")
          lesson.value.status = "published"
        })
      }
      const unPublish = () => {
        unPublishLesson({id: lesson.value.id}, () => {
          success("取消发布成功")
          lesson.value.status = "unpublished"
        })
      }
      // 步骤条
      const steps = [
        {key: "base", name: "基础信息"},
        {key: "content", name: "课程章节"},
        {key: "publish", name: "发布"},
      ]
      const stepActive = ref(0)
      const loadStepActiveArray = () => {
        const stepActiveArray = [];
        for (let i = 0; i < steps.length; i++) {
          const step = steps[i];
          stepActiveArray.push(step.key);
          if (step.key === showStep.value) {
            stepActive.value = i;
            break;
          }
        }
        if (isUpdate) {
          stepActive.value = steps.length;
        }
        return stepActiveArray;
      }
      const init = () => {
        // 初始化加载
        if (route.query.step) {
          showStep.value = route.query.step;
        } else {
          showStep.value = "base"
        }
        lesson.value.id = route.query.id || ""
        loadCategory();
        loadContent();
      }
      init()
      // 步骤条点击切换
      const stepClick = (key) => {
        if (!isUpdate && loadStepActiveArray().indexOf(key) < 0) {
          return;
        }
        showStep.value = key;
        let path = route.fullPath;
        router.push({path, query: {id: lesson.value.id, step: key} });
      }
      loadStepActiveArray();
      // 返回参数与方法
      return {
        // 基本信息
        uploadData,
        categoryOptions,
        lesson,
        selectCidList,
        lessonRules,
        lessonRef,
        changeCategory,
        changeStartTime,
        changeEndTime,
        onUploadImageSuccess,
        onUploadImageRemove,
        submitBaseInfo,
        // 内容列表
        contentList,
        showChapterDialog,
        lessonChapter,
        lessonChapterRules,
        showChapterSectionDialog,
        lessonChapterSection,
        lessonChapterSectionRules,
        lessonChapterRef,
        lessonChapterSectionRef,
        showChapter,
        hideChapter,
        showChapterSection,
        hideChapterSection,
        deleteChapter,
        deleteChapterSection,
        submitChapter,
        submitChapterSection,
        uploadVideoData,
        lessonChapterSectionUrlType,
        onUploadVideoSuccess,
        onUploadVideoRemove,
        onBeforeUploadVideo,
        // 发布页面
        statusMap,
        publish,
        unPublish,
        // 步骤条
        steps,
        stepActive,
        showStep,
        stepClick,
        uploadHomeworkData,
        onUploadHomeworkAttachmentSuccess,
        onUploadHomeworkAttachmentRemove
      };
    }
  }
</script>
<style scoped>
  .upload-image-tips {
    font-size: 12px;
    color: #999999;
  }
  .el-form-item {
    width: 96%;
  }
  >>> .el-input--mini .el-input__inner {
    height: 40px;
  }
  >>> .el-step.is-vertical .el-step__title{
    cursor:pointer;
  }
  >>> .el-step.is-vertical .el-step__line {
    width: 1px;
  }
  >>> .el-step__icon.is-text {
    border-width: 1px;
    cursor:pointer;
  }
  >>> .el-upload--picture-card, >>> .el-upload-list--picture-card .el-upload-list__item {
    width: 100%;
    height: 62.5%;
  }
  >>> .step-active .el-step__head.is-finish {
    color: red;
  }
  .tips {
    font-size: 12px;
    color: #999999;
  }
</style>
